﻿/****************************************************************************
 * MainServerThread
 * Sets up a server listeníng for incoming connections and dispatches new connections
 * as a new ClientConnectionHandler thread
 * 
 * 20110526 - md - Initial version 
 * *************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;

namespace KinectMsSdkServer
{
    class MainServerThread
    {
        ArrayList connections;


        TcpListener serverSocket;
        private KinectHandler kinectHandle;

        public MainServerThread(KinectHandler kinectHandle)
        {
            Console.WriteLine("Trying to bind to port 12345");

            serverSocket = new TcpListener(IPAddress.Any, 12345);
            serverSocket.Start();
            Console.WriteLine("Socket successfully bound");
            this.kinectHandle = kinectHandle;
            Console.WriteLine("Server thread initiated");
            connections = new ArrayList();

        }

        public ArrayList getConnections()
        {
            return this.connections;
        }

        public void distribute(String cmd)
        {
            foreach (ClientConnectionHandler cch in connections)
            {
                cch.distribute(cmd);
            }
        }
        public void awaitConnections()
        {
            while (true)
            {
                if (serverSocket.Pending())
                {
                    try
                    {
                        TcpClient clientSocket = serverSocket.AcceptTcpClient();
                        IPEndPoint e = (IPEndPoint)clientSocket.Client.RemoteEndPoint;
                        Console.WriteLine("Connect from " + e.Address + ":" + e.Port);

                        ClientConnectionHandler cch = new ClientConnectionHandler(clientSocket, kinectHandle, this);
                        connections.Add(cch);
                        cch.DisconnectedEvent += onClientDisconnect;

                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error during connection setup: " + e.Message);
                    }
                }
            }
        }

        void onClientDisconnect(object sender, EventArgs e)
        {
            try
            {
                connections.Remove(sender);
                Console.WriteLine("Client connection removed!");
            }
            catch (Exception)
            {
            }
        }
    }
}
